package xyz.liuz.edb;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class ServiceEncoder extends MessageToByteEncoder<String> {


    @Override
    protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out) throws Exception {
        System.out.println("编码器运行啦----"+msg);
//        int msgLength = msg.getBytes("UTF-8").length;
//        String headLength = frontCompWithZore(msgLength,6);
//        byte[] dataLength = headLength.getBytes();
//        byte[] data = msg.getBytes("UTF-8");
//        out.writeBytes(dataLength);
//        out.writeBytes(data);


//        String sendMsg = "000012EDB";
//        byte[] sendData = sendMsg.getBytes();
//        out.writeBytes(sendData);

//          int messageType = 1;
//          out.writeInt(messageType);
          out.writeBytes(int2ByteArray(1123114531));
          int messageLength = msg.getBytes("UTF-8").length;
          out.writeInt(messageLength);
          byte[] data = msg.getBytes("UTF-8");
          out.writeBytes(data);


    }

    public static String frontCompWithZore(int sourceDate,int formatLength) {
        //0 指前面补充零
        //formatLength 字符总长度为 formatLength
        //d 代表为正数。
        String newString = String.format("%0" + formatLength + "d", sourceDate);
        return newString;
    }
    public static byte[] int2ByteArray(int i){
        byte[] result=new byte[4];
        result[0]=(byte)((i >> 24)& 0xFF);
        result[1]=(byte)((i >> 16)& 0xFF);
        result[2]=(byte)((i >> 8)& 0xFF);
        result[3]=(byte)(i & 0xFF);
        return result;
    }

}
